import React from "react";
import style from "./index.module.scss";
import {Image} from "antd";
const imgFallback = require("../../common/imageDefault/book-cover-default.png").default

import {Map, Marker, Markers, MouseTool, InfoWindow} from "react-amap";
import "./mapstylefix.scss";

/* MouseTool
    需要在地图上启用鼠标工具插件时使用；
    启用该插件可以进行鼠标画标记点、线、多边形、矩形、圆、距离量测、面积量测、拉框放大、拉框缩小等功能。

    key = f97efc35164149d0cOf299e7a8adb3d2
    key = 12345678d98aff1166e51962f108bb24
*/ 

import { Toast } from 'antd-mobile';
const failToast = () => {
    Toast.fail('获取数据失败！', 2);
}

class MapGD extends React.Component{
    constructor(props){
        super(props);
        this.props=props;
        const self =this;

        this.state = {
            mapCenter:{ longitude: 116.25014, latitude: 40.11623 },
            zooms:[13,26],
            mapPlugins:['ToolBar'],
            what: '附近在售的图书',
            markPosition:[],
            offset: [0, 0],
            useCluster:true,
            status: { //是否支持放大拖拽
                zoomEnable: true,
                dragEnable: true,
            },
            mapMaker :[  //marker标记点(list)
                {lnglat:[116.401728,39.911984],text:'要显示的内容1'},
                {lnglat:[116.436691,39.921984],text:'要显示的内容2'}
            ],
        };

        this.toolEvents = {
            created: (tool) => {
              self.tool = tool;
            },
            draw({obj}) {
              self.drawWhat(obj);
            }
        };
        this.amapEvents = {
            created: (mapInstance) => {
              console.log(mapInstance.getZoom());
            },
        };
        this.markerEvents = {
            created: (markerInstance) => {
              console.log(markerInstance.getPosition());
            },
            click:(e)=>{
                console.log("markClick",e.target.w.extData);
                this.props.history.push("/bookInfoDetails/"+e.target.w.extData)
            }
        };
        this.markersEvents = {
            created:(allMarkers) => { 
                console.log('All Markers Instance Are Below');
                // console.log(allMarkers);
            },
            click: (MapsOption, marker) => {
                let bid;
                if(MapsOption) bid = MapsOption.target.w.extData.myIndex;
                else if(marker) bid =  marker.w.extData.myIndex;
                if(bid) this.props.history.push("/bookInfoDetails/"+ bid);
                else failToast();
            },
            dragend: (MapsOption, marker) => { /* ... */ }
          }
    }

    // 解析地图绘画元素信息--展示信息
    drawWhat(obj) {
        let text = '';
        switch(obj.CLASS_NAME) {
          case 'AMap.Marker':
           text = `你绘制了一个标记，坐标位置是 {${obj.getPosition()}}`;
           break;
          case 'AMap.Polygon':
            text = `你绘制了一个多边形，有${obj.getPath().length}个端点`;
            break;
          case 'AMap.Circle':
            text = `你绘制了一个圆形，圆心位置为{${obj.getCenter()}}`;
            break;
          default:
            text = '';
        }
        let markPosition = obj.getPosition();
        this.setState({
          what: text, markPosition
        });
        setTimeout(()=>{
            console.log(this.state.markPosition);
        });
    }
    
    // 绑定绘制 Marker点事件
    drawMarker(){
        console.log("准备绘制坐标点")
        if (this.tool){
            this.tool.marker();
            this.setState({
                what: '准备绘制坐标点'
            });
        }
    }

    // 搜索相关 -- 暂时未引用
    selectAddress(){
        // created必须要拥有,用来初始化创建相应对象
        created: () => {
            let auto
            let placeSearch
            window.AMap.plugin('AMap.Autocomplete', () => {
                auto = new window.AMap.Autocomplete({
                    input: 'tipinput',
                    pageSize: 10,
                    pageIndex: 1,
                    citylimit: true,    // 仅搜索本城市的地名
                    city:'北京', // 限制为只能搜索当前地区的位置
                    outPutDirAuto: true,
                    type: '汽车服务|汽车销售|汽车维修|摩托车服务|餐饮服务|购物服务|生活服务|体育休闲服务|医疗保健服务|住宿服务|风景名胜|商务住宅|政府机构及社会团体|科教文化服务|交通设施服务|金融保险服务|公司企业|道路附属设施|地名地址信息|公共设施'
                });
            })
            // 创建搜索实例
            window.AMap.plugin('AMap.PlaceSearch', () => {
                placeSearch = new window.AMap.PlaceSearch({
                    input: 'tipinput',
                    pageSize: 10,
                    pageIndex: 1,
                    citylimit: true,    // 仅搜索本城市的地名
                });
            })

            window.AMap.event.addListener(auto, "select", (e) => {
                placeSearch.search(e.poi.name)
            })
        }
    }

    windowEvents = {
        // created: (iw) => {console.log(iw)},
        open: () => {console.log('InfoWindow opened')},
        close: () => {console.log('InfoWindow closed')},
        change: () => {console.log('InfoWindow prop changed')},
    } 

    static defaultProps = {
        bookList:[]
    }

    componentDidMount(){
       setTimeout(()=>{
        // this.drawMarker();
        // console.log("window.AMap-->", window.AMap);
       },500);
    }


    renderMarkerLayout(extData){
        return (
            <div className={style["marker-content"]}>
                <img className={style["markbg"]} src={require("../../common/image/map/mark_bs.png").default} />
                <Image preview={false} className={style["bookcover"]} src={`/apis/${extData.cover}`} fallback={imgFallback} />
                <span>{extData.myLabel}</span>
            </div>
        )
    }

    sendData(bid){
        return this.prop.bookList.find(item => item.bid === bid);
    }

    render(){
        // 地图配置 暂时未引用
        let mapData = {
            city: "北京",
            mapCenter:[116.418261, 39.921984],  //城市定位，经纬度定位只能选择1个
            mapZoom: 10, //地图缩放
            mapKey: '12345678d98aff1166e51962f108bb24',   //你的高德key
            status: { //是否支持放大拖拽
                zoomEnable: true,
                dragEnable: true,
            },
            mapMaker :[  //marker标记点(list)
                {lnglat:[116.401728,39.911984],text:'要显示的内容1'},
                {lnglat:[116.436691,39.921984],text:'要显示的内容2'}
            ],
            plugins:['ToolBar']
        };
        
        // Markers 组件数据
        let {bookList} = this.props;
        let bookItems = bookList.map((book,i)=>{
            return {
                position:JSON.parse(book.position),
                myIndex:book.bid,
                myLabel:book.name,
                cover:book.cover,
                contnet:`<span>${book.name}</span>`,
            }
        })

        return (
            <div className={style["index-root"]}>
                <div className={style["map-box"]}>
                    <Map plugins={this.state.mapPlugins}
                        // mapData ={this.state}
                        center={this.state.mapCenter} events={this.amapEvents}
                        zooms={this.state.zooms} 
                        events={this.toolEvents}
                        extData={bookList}

                     >
                         <MouseTool events={this.toolEvents}/>
                         <div className={style["what-box"]}>{this.state.what}</div>

                            {/* {bookMarker} */}

                            <Markers 
                                markers={bookItems}
                                useCluster={this.state.useCluster}
                                render={this.renderMarkerLayout}
                                events={this.markersEvents}
                            />
                    </Map>
                </div>

                <div className={style["op-box"]} >
                    <button ref={drawMarkerBtn=>this.drawMarkerBtn=drawMarkerBtn} 
                        onClick={()=>{this.drawMarker()}}>手动画锚点
                    </button>
                </div>
            </div>
        )
    }
}

export default MapGD;